package com.zlwy.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zlwy.adapter.FiveAdapter;
import com.zlwy.application.GlobalApplication;
import com.zlwy.debug.Logger;
import com.zlwy.dialog.T_InfoDialog;
import com.zlwy.entity.C_Result;
import com.zlwy.entity.Five;
import com.zlwy.entity.Grid;
import com.zlwy.entity.Price;
import com.zlwy.entity.Trade;
import com.zlwy.entity.User;
import com.zlwy.entity.YBEntity;
import com.zlwy.http.InfoRequest;
import com.zlwy.http.MarqueeRequest;
import com.zlwy.util.DateUtil;
import com.zlwy.util.Util;
import com.zlwy.view.AutoScrollTextView;
import com.zlwy.view.GridChart;
import com.zlwy.view.VectorLineView;

/**
 * @author acer
 *
 */
public class HomeFragment extends Fragment implements OnClickListener{

	private User user;
	private View homeView;
	private RelativeLayout layoutBusy;
	private RelativeLayout layoutInfo;
	private ListView lvFive;
	private FiveAdapter fAdapter;
	private boolean isLogin;
	private int wId = 0;
	private int pId = 0;
	private int imId = 0;
	private Price mPrc;
	private Trade trade;
	private Timer pTimer;
	private Timer fTimer;
	private String stm;
	/**
	 * 分时图计时器
	 */
	private Timer imTimer;
	private List<Five> fives = new ArrayList<>();
	private List<Five> buyFives = new ArrayList<>();
	private List<Five> sellFives = new ArrayList<>();
	private TextView tvMax;//最高价
	private TextView tvMin;//最低价
	private TextView tvNow;//现价
	private TextView tvSwing;//涨幅
	private TextView tvRise;//涨跌差
	private TextView tvEqually;//均价
	private TextView tvHNow;
	private TextView tvHSwing;
	private TextView tvHRise;
	private TextView tvNum;
	private TextView tvTm;
	private ImageView ivFive;
	private ImageView ivDetail;
	private Button btnFive;
	private Button btnDetail;
	//服务器时间
	private String svTime;
	private List<YBEntity> ybList = new ArrayList<YBEntity>();
	
	private GridChart gChart;
	private Grid topGrid;
	private VectorLineView vectorLine;
	private String[] marquees = new String[3];//跑马灯;
	private AutoScrollTextView autoScrollTextView;
	private int moveIndex = 0;
	private boolean isOpen = false;
	private boolean isFirst = true;
	
	private Handler mHandler = new Handler(){		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 0:
					Toast.makeText(getActivity(), "连接服务器失败,请检查网络", Toast.LENGTH_SHORT).show();
					break;
				case 1:
					//接收到分时图广播，更新K线图
					if(isFirst&&!isOpen&&ybList.size()<=0){
						Toast.makeText(getActivity(), "暂未开盘", Toast.LENGTH_SHORT).show();
						isFirst = false;
					}
					if(ybList.size()<=0){
						//证明没有数据,证明不用更新了
						return;
					}	
					ybList.get(0).setTm(postponeOpenTime(ybList.get(0).getTm()));
					if(ybList.size()==1){
						//证明只有一条数据
						onlyOneData();
					}
					if(ybList.size()>1){
						//证明有多条数据,要计算每个数据之间有没有时差
						moreThanOneData();
					}
					gChart.setData(ybList);
					setBottomText(ybList.size()-1);
					setVectorLine();
					break;
				case 8:
					//获取到大盘信息,之后就要获取价格信息,获取图表信息
					sendPriceWebSocketMessage();
					sendIMWebSocketMessage();
					sendFiveWebSocketMessage();
					Intent intent = new Intent("COM.ZLWY.T_INFO_OK");
					getActivity().sendBroadcast(intent);
					break;
				case 9:
					
					break;
				case 11:
					//接收到5档广播
					fives.clear();
					sort();
					setDatas();			
					fAdapter = new FiveAdapter(fives, getActivity());
					lvFive.setAdapter(fAdapter);
					break;
				case 12:
					//接到价格广播,每次价格变动都要更新涨跌幅，还要在这里做K线图更新	
					setTopText();
					initGrip();
					gChart.setGrid(topGrid);
					break;
				case 14:
					//获取跑马灯成功					
				    if(marquees!=null){ 
				        autoScrollTextView.initScrollTextView(getActivity().getWindowManager(), marquees); 
				        autoScrollTextView.starScroll(); 
				    }
					break;
				case 15:
					//接到量线移动广播
					setBottomText(moveIndex);
					break;
			}
		};
	};
	/**
	 * 五档广播
	 */
	private BroadcastReceiver fiveReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			//接收到数据广播，要解析数据
			JSONObject json = null;
			JSONObject msg = null;
			try {
				json = new JSONObject(intent.getStringExtra("JSON"));
				if(json!=null&&!json.isNull("msg"))
					msg = new JSONObject(json.getString("msg"));		
			}catch (JSONException e1) {
				e1.printStackTrace();			
			}
			try {
				if(msg!=null&&!msg.isNull("buy")){
					if(msg.getString("buy").trim().equals("{}")){
						//返回一对大括号
						buyFives.clear();
					}else{
						JSONArray buys = new JSONArray(msg.getString("buy"));
						if(buys!=null&&buys.length()>0){
							buyFives.clear();
							for(int i=0; i<buys.length(); i++){
								
								JSONObject obj = buys.getJSONObject(i);
								Five bf = new Five();
								if(!obj.isNull("type")){
									bf.setType(obj.getString("type"));
									bf.setTypes(1);
								}
								if(!obj.isNull("prc")){
									bf.setPrice(obj.getString("prc"));
								}
								if(!obj.isNull("num")){
									bf.setNum(obj.getString("num"));
								}
								buyFives.add(bf);
							}
						}
					}
					
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			try {
				if(msg!=null&&!msg.isNull("sell")){
					if(msg.getString("sell").trim().equals("{}")){
						//返回一对大括号
						sellFives.clear();
					}else{
						JSONArray sales = new JSONArray(msg.getString("sell"));
						if(sales!=null&&sales.length()>0){
							sellFives.clear();
							for(int i=0; i<sales.length(); i++){									
								JSONObject obj = sales.getJSONObject(i);
								Five sf = new Five();
								if(!obj.isNull("type")){
									sf.setType(obj.getString("type"));
									sf.setTypes(2);
								}
								if(!obj.isNull("prc")){
									sf.setPrice(obj.getString("prc"));
								}
								if(!obj.isNull("num")){
									sf.setNum(obj.getString("num"));
								}
								sellFives.add(sf);
							}
						}
					}							
				}
			} catch (JSONException e) {
					e.printStackTrace();
			}
		mHandler.sendEmptyMessage(11);
		}	
	};
	/**
	 * 最高价、最低价、现价广播
	 */
	private BroadcastReceiver pReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			try {
				JSONObject json = new JSONObject(intent.getStringExtra("JSON"));
				if(json!=null&&!json.isNull("msg")){
					JSONObject obj = new JSONObject(json.getString("msg"));
					if(obj!=null){
						if(!obj.isNull("min_prc")){
							String mprc = obj.getString("min_prc");
							mPrc.setMinPrc(Util.dealStrs(mprc, 3));
						}
						if(!obj.isNull("max_prc")){
							String mprc = obj.getString("max_prc");
							mPrc.setMaxPrc(Util.dealStrs(mprc, 3));
						}
						if(!obj.isNull("cur_prc")){
							String mprc = obj.getString("cur_prc");
							mPrc.setNowPrc(Util.dealStrs(mprc, 3));
						}
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mHandler.sendEmptyMessage(12);
		}
		
	};
	/**
	 * 分时图广播接收器
	 */
	private BroadcastReceiver imReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			svTime =Util.utc2Local(intent.getStringExtra("STM"));
			try {
				JSONObject json = new JSONObject(intent.getStringExtra("JSON")); 
				JSONArray arr = null;
				if(json!=null&&!json.isNull("msg")&&!json.getString("msg").trim().equals("{}")){
					 arr = json.getJSONArray("msg");
				}
				if(arr!=null)
				if(arr.length()>0){
					ybList.clear();
					for(int i=0; i<arr.length(); i++){
						JSONObject obj = arr.getJSONObject(i);
						if(obj!=null){
							YBEntity yb = new YBEntity();
							if(!obj.isNull("tm")){									
								yb.setTm(Util.utc2Local(obj.getString("tm")));
							}
							if(!obj.isNull("cur_prc")){									
								yb.setCur_prc(obj.getString("cur_prc"));
								if(yb.getCur_prc().equals("0")&&trade!=null){
									yb.setCur_prc(trade.getOpen_price());
								}
							}
							if(!obj.isNull("avg_prc")){
								yb.setAvg_prc(obj.getString("avg_prc"));
							}
							if(!obj.isNull("sum_num")){
								yb.setTrd_num(obj.getString("sum_num"));
							}
							if(!obj.isNull("sum_prc")){
								yb.setTrd_cash(obj.getString("sum_prc"));
							}
							if(!obj.isNull("quote_change")){
								yb.setRatio(obj.getString("quote_change"));
							}
							
							if(ybList.size()>0&&ybList.get(ybList.size()-1).getTm().equals(yb.getTm())){
								yb.setTm(Util.utcEndMinutel(obj.getString("tm")));
							}
							ybList.add(yb);
						}
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			mHandler.sendEmptyMessage(1);	
		}		
	};
	
	private BroadcastReceiver moveReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			moveIndex = intent.getIntExtra("INDEX", ybList.size()-1);
			if(moveIndex>=ybList.size()){
				moveIndex=ybList.size()-1;
			}
			mHandler.sendEmptyMessage(15);
		}		
	};
	
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	public void setUser(User user){
		this.user = user;
		if(user!=null){
			isLogin = true;
		}else{
			isLogin = false;
		}
	}
	
	@SuppressLint("InflateParams")
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if(homeView==null){
			homeView = inflater.inflate(R.layout.home, null);
			initView();			
			mPrc = new Price();
			initFiveReceiver();
			initPReceiver();
			initImReceiver();
			initMoveReceiver();
			new InfoTask().execute();
			new MarqueeTask().execute();	
		}	
		return homeView;
	}
	
	private void initMoveReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.CHARTMOVE");
		getActivity().registerReceiver(moveReceiver, filter);
	}
	
	private void initFiveReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.PUSH_FIVE");
		getActivity().registerReceiver(fiveReceiver, filter);
	}
	
	private void initPReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.PUSH_PRC");
		getActivity().registerReceiver(pReceiver, filter);
	}
	
	private void initImReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction("COM.ZLWY.PUSH_IM");
		getActivity().registerReceiver(imReceiver, filter);
	}
	
	private void initView(){
		layoutBusy = (RelativeLayout) homeView.findViewById(R.id.layoutBusiness);
		layoutBusy.setOnClickListener(this);
		layoutInfo = (RelativeLayout) homeView.findViewById(R.id.layoutConjunctureDetail);
		layoutInfo.setOnClickListener(this);
		lvFive = (ListView) homeView.findViewById(R.id.lvCData);
		tvMax = (TextView) homeView.findViewById(R.id.conjunctureMax);
		tvMin = (TextView) homeView.findViewById(R.id.conjunctureMin);
		tvNow = (TextView) homeView.findViewById(R.id.conjunctureNow);		
		tvSwing = (TextView) homeView.findViewById(R.id.conjunctureRange);
		tvRise = (TextView) homeView.findViewById(R.id.conjunctureUp);
		
		tvEqually = (TextView) homeView.findViewById(R.id.conjunctureEquallyPrice);
		tvHNow = (TextView) homeView.findViewById(R.id.conjunctureNews);
		tvHRise = (TextView) homeView.findViewById(R.id.conjunctureNewUp);
		tvHSwing = (TextView) homeView.findViewById(R.id.conjunctureNewRange);
		tvNum = (TextView) homeView.findViewById(R.id.tvTotalNum);
		tvTm = (TextView) homeView.findViewById(R.id.tvHomeTm);
		
		ivFive = (ImageView) homeView.findViewById(R.id.ivFiveGrade);
		ivFive.setVisibility(View.VISIBLE);
		ivDetail = (ImageView) homeView.findViewById(R.id.ivCDetail);
		
		btnFive = (Button) homeView.findViewById(R.id.btnFiveGrade);
		btnFive.setOnClickListener(this);
		btnDetail = (Button) homeView.findViewById(R.id.btnCDetail);
		btnDetail.setOnClickListener(this);
		
		autoScrollTextView = (AutoScrollTextView) homeView.findViewById(R.id.autoScroll);
		
		gChart = (GridChart) homeView.findViewById(R.id.grid);
		gChart.setOnClickListener(this);
		gChart.setContext(getActivity());
		vectorLine = (VectorLineView) homeView.findViewById(R.id.vectorLine);
		vectorLine.setFocusable(false);
		gChart.setVctView(vectorLine);
	}
	/**
	 * 设置最上方的数值
	 */
	private void setTopText(){
		String max = mPrc.getMaxPrc();
		String min = mPrc.getMinPrc();
		String now = mPrc.getNowPrc();
		String open = trade.getOpen_price();
		if(open!=null&&!open.equals("")){
			double openPrc = Double.parseDouble(trade.getOpen_price());
			double nowPrc = 0.00f;
			double minPrc = 0.00f;
			double maxPrc = 0.00f;
			
			if(now==null||now.equals("")){
				nowPrc = openPrc;
			}else{
				nowPrc = Double.parseDouble(now);
			}							
			if(min==null||min.equals("")){
				minPrc = openPrc;
			}else{
				minPrc = Double.parseDouble(min);
			}				
			if(max==null||max.equals("")){
				maxPrc = openPrc;
			}else{
				maxPrc = Double.parseDouble(max);
			}			
			if(minPrc>openPrc){
				tvMin.setTextColor(Util.getResourcesColor(R.color.red));
			}else{
				tvMin.setTextColor(Util.getResourcesColor(R.color.green));
			}
			if(maxPrc>=openPrc){
				tvMax.setTextColor(Util.getResourcesColor(R.color.red));
			}else{
				tvMax.setTextColor(Util.getResourcesColor(R.color.green));
			}
			if(nowPrc>=openPrc){
				tvNow.setTextColor(Util.getResourcesColor(R.color.red));
				tvRise.setTextColor(Util.getResourcesColor(R.color.red));
				tvSwing.setTextColor(Util.getResourcesColor(R.color.red));			
			}else{
				tvNow.setTextColor(Util.getResourcesColor(R.color.green));
				tvRise.setTextColor(Util.getResourcesColor(R.color.red));
				tvSwing.setTextColor(Util.getResourcesColor(R.color.red));
			}
			tvMin.setText(min);
			tvNow.setText(now);
			tvMax.setText(max);
			tvRise.setText(Util.dealStrs(nowPrc-openPrc+"", 3));
			tvSwing.setText(Util.dealStrs((nowPrc-openPrc)/openPrc*100+"", 3)+"%");
		}else{
			tvMax.setText("0.00");
			tvMin.setText("0.00");
			tvNow.setText("0.00");
			tvRise.setText("0.00");
			tvSwing.setText("0.00%");
		}
		
	}
	
	/**
	 * 设置下方的数值,这里的数值会根据量线变化
	 */
	private void setBottomText(int index){
		int size = ybList.size();
		if(index>size-1){
			index = size-1;
		}
		if(size>0){
			tvEqually.setText(ybList.get(index).getAvg_prc());
			tvHNow.setText(ybList.get(index).getCur_prc());
			double nowPrc = Double.parseDouble(ybList.get(index).getCur_prc());
			double openPrc = Double.parseDouble(trade.getOpen_price());
			tvHRise.setText(Util.dealStrs((nowPrc-openPrc)+"", 3));
			tvHSwing.setText(Util.dealStrs((nowPrc-openPrc)/openPrc*100+"", 3)+"%");
			tvNum.setText(ybList.get(index).getTrd_num());
			tvTm.setText(ybList.get(index).getTm());
		}else{
			tvEqually.setText("0.00");
			tvHNow.setText("0.00");
			tvHRise.setText("0.00");
			tvHSwing.setText("0.00%");
		}
	}
	/**
	 * 设置方框内的几个值
	 */
	private void initGrip(){
		topGrid = new Grid();
		String max = mPrc.getMaxPrc();
		String min = mPrc.getMinPrc();
		String open = trade.getOpen_price();
		if(open!=null&&!open.equals("")){
			topGrid.setCenterValue(trade.getOpen_price());
			double xPrc = 0.00f;
			double nPrc = 0.00f;
			double oPrc = Double.parseDouble(trade.getOpen_price());
			if(max!=null&&!max.equals("")){
				xPrc = Double.parseDouble(max);			
			}else{
				xPrc = Double.parseDouble(open);
			}		
			if(mPrc.getMinPrc()!=null&&!mPrc.getMinPrc().equals("")){
				nPrc = Double.parseDouble(mPrc.getMinPrc());			
			}else{
				nPrc = Double.parseDouble(open);
			}
			if(oPrc==xPrc&&oPrc==nPrc){
				max = Util.dealStrs((oPrc+(0.1f*oPrc))+"", 3);
				min = Util.dealStrs((oPrc-(0.1f*oPrc))+"", 3);
				xPrc = Double.parseDouble(max);
				nPrc = Double.parseDouble(min);
			}
			double maxRise = Util.dealDouble(xPrc-oPrc, 3);
			double minRise = Util.dealDouble(nPrc-oPrc, 3);
			double tRiseRange = 0.0f;
			if(maxRise+minRise>=0){
				//证明涨幅大
				tRiseRange = (maxRise/oPrc)*100;
				min = Util.dealStrs((oPrc-maxRise-maxRise*0.05f)+"", 3);
				max = Util.dealStrs((xPrc+maxRise*0.05f)+"", 3);
			}else{
				//证明跌幅大
				tRiseRange = (minRise/oPrc)*100;
				min = Util.dealStrs((nPrc+minRise*0.05f)+"", 3);
				max = Util.dealStrs(oPrc-minRise-minRise*0.05f+"", 3);
			}		
			if(tRiseRange>=0){
				String riseRange = Util.dealStrs(tRiseRange+"", 2);
				topGrid.setRizeUp(riseRange+"%");
				topGrid.setRizeDown("-"+riseRange+"%");
			}else{
				String riseRange = Util.dealStrs(-tRiseRange+"", 2);
				topGrid.setRizeUp(riseRange+"%");
				topGrid.setRizeDown("-"+riseRange+"%");
			}
			topGrid.setMaxValue(max);
			topGrid.setMingValue(min);
			topGrid.setCenterValue(open);
		}else{
			//证明闭市了
			topGrid.setMaxValue("0.00");
			topGrid.setMingValue("0.00");
			topGrid.setCenterValue("0.00");
			topGrid.setRizeUp("0.00%");
			topGrid.setRizeDown("-0.00%");
		}
		
	}
	/**
	 * 设置量的数据
	 */
	private void setVectorLine(){
		vectorLine.setData(ybList);
		double max = 10f;
		if(ybList.size()>0){
			for(YBEntity e:ybList){
				double num = Double.parseDouble(e.getTrd_num());
				if(num>max){
					max = num;
				}
			}
		}		
		Grid grid = new Grid();
		grid.setMaxValue(max+"");
		grid.setCenterValue(trade.getOpen_price());
		vectorLine.setGrid(grid);
	}
	
	/**
	 * 设置数据
	 */
	private void setDatas(){
		int sIndex = sellFives.size();
		for(int i=0; i<5-sIndex; i++){
			sellFives.add(new Five("", "", "", 2));
		}
		for(int i=0; i<5; i++){
			sellFives.get(i).setType("卖("+(i+1)+")");
		}
		Collections.reverse(sellFives);
		for(Five f:sellFives){
			fives.add(f);
		}
		
		int bIndex = buyFives.size();
		for(int i=0; i<5-bIndex; i++){
			buyFives.add(new Five("", "", "", 1));
		}
		for(int i=0; i<5; i++){
			buyFives.get(i).setType("买("+(i+1)+")");
			fives.add(buyFives.get(i));
		}
	}
	/**
	 * 五档排序
	 */
	private void sort(){
		Comparator<Five> comp = new Comparator<Five>() {
			public int compare(Five f1, Five f2) {
				if(f1.getPrice().equals("")||f2.getPrice().equals("")){
					return 0;
				}
				double t1 = Double.parseDouble(f1.getPrice());
				double t2 = Double.parseDouble(f2.getPrice());
				if(t1<t2){
					return 1;
				}else if(t1==t2){
					return 0;
				}else{
					return -1;
				}
			}
		};
	    Collections.sort(buyFives,comp);
	    Collections.sort(sellFives,comp);
	    Collections.reverse(sellFives);
	}
	
	/**
	 * @param num 追加数据量
	 * @param start 起始位置
	 */
	private void addData(int num, int start){
		//追加数据			
		for(int i=0; i<num; i++){
			YBEntity yb = new YBEntity();
			String time = ybList.get(start+i).getTm();
			String price = ybList.get(start+i).getAvg_prc();
			String nPrice = ybList.get(start+i).getCur_prc();
			//往后推移一分钟
			time = postponeOneMinue(time);
			yb.setAvg_prc(price);
			yb.setCur_prc(nPrice);
			yb.setTm(time);
			yb.setTrd_num("0");
			ybList.add(start+i+1, yb);
		}		
	}
	
	/**
	 * 有多条数据
	 */
	private void moreThanOneData(){
		int size = ybList.size();
		int index = ybList.size();	
		//先追加开盘时间到第一条成交价的时间的数据
		int num = 0;
		for(int i=1; i<size; i++){
			num = getDiffMinue(ybList.get(i-1).getTm(), ybList.get(i).getTm())-1;
			addData(num, i-1);
			if(index>0){
				//证明后面还有数据，需要继续追加，这时候追加的位置要发生改变了	
				i = ybList.size()-index+1;
				size = ybList.size();
				index--;
			}			
		}
		//数据加载完了还要计算当前时间和最后一条数据之间的数据,这个时候是往集合里面直接加入数据
		size = ybList.size();
		num = getDiffMinue(ybList.get(size-1).getTm(), svTime);
		addData(num, size-1);
	}
	
	/**
	 * 计算两个时间的分钟差
	 */
	private int getDiffMinue(String start, String end){
		int num = 0;
		Date starts = DateUtil.parse(start);
		Date ends = DateUtil.parse(end);
		if(starts!=null&&ends!=null){
			long diff = (ends.getTime() - starts.getTime());
			num = (int) (diff/60000);
		}
		return num;
	}
	/**
	 * 往后推迟一分钟
	 */
	private String postponeOneMinue(String time){
		Date tm = DateUtil.parse(time);
		if(tm!=null){
			long t = tm.getTime()+60000;
			Date d = new Date(t);
			time = DateUtil.format(d);
		}
		return time;
	}
	/**
	 * 往后推迟12个小时
	 */
	private String postponeOpenTime(String time){
		Date tm = DateUtil.parse(time);
		if(tm!=null){
			long t = tm.getTime()+43200000;
			Date d = new Date(t);
			time = DateUtil.format(d);
		}
		return time;
	}
	
	/**
	 * 仅有一条数据
	 */
	private void onlyOneData(){
		int num = getDiffMinue(ybList.get(0).getTm(), svTime);
		addData(num, 0);
	}
	
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.layoutBusiness:
				if (isLogin) {
					Intent intent = new Intent(getActivity(), BusinessActivity.class);
					Bundle b = new Bundle();
					b.putSerializable("USER", user);
					b.putSerializable("TRADE", trade);
					intent.putExtras(b);
					getActivity().startActivity(intent);
				}else{
					Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
				}			
				break;
			case R.id.btnFiveGrade:
				//五档
				ivFive.setVisibility(View.VISIBLE);
				ivDetail.setVisibility(View.INVISIBLE);
				break;
			case R.id.btnCDetail:
				//明细
				ivDetail.setVisibility(View.VISIBLE);
				ivFive.setVisibility(View.INVISIBLE);
				break;
			case R.id.layoutConjunctureDetail:
				new T_InfoDialog(getActivity(), R.style.infodialog, mPrc).show();
				break;
		}
	}
	
	/**
	 * 发送价格请求
	 */
	private void sendPriceWebSocketMessage(){
		pTimer = new Timer();
		pTimer.schedule(new TimerTask() {
			public void run() {		
				if(pId>=1800){
					pId = 0;
				}
				JSONObject obj = new JSONObject();
				try {					
					obj.put("_id_", pId+"");
					obj.put("action", "Trends.getRTTradeInfo");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
				if(obj.toString()!=null&&GlobalApplication.client.getSokect()!=null&&GlobalApplication.client!=null){
					GlobalApplication.client.getSokect().sendTextMessage(obj.toString());
					pId += 1;
				}
			}
		}, 1, 30000);
	}
	
	/**
	 * 发送五档请求
	 */
	private void sendFiveWebSocketMessage(){
		wId = 1800;
		fTimer = new Timer();
		fTimer.schedule(new TimerTask() {
			public void run() {		
				if(wId>= 3600){
					wId = 1800;
				}
				JSONObject obj = new JSONObject();
				try {					
					obj.put("_id_", wId+"");
					obj.put("action", "Trends.getRTBuySellInfo");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
				GlobalApplication.client.getSokect().sendTextMessage(obj.toString());
				wId += 1;
			}
		}, 1, 30000);
	}
	/**
	 * 分时图请求
	 */
	private void sendIMWebSocketMessage(){			
		imId = 5400;
		imTimer = new Timer();
		imTimer.schedule(new TimerTask() {
			public void run() {	
				if(imId>=7200){
					imId =5400;
				}
				JSONObject obj = new JSONObject();
				try {					
					obj.put("_id_", imId+"");
					obj.put("action", "Trends.getOneMinInfo");
					stm ="0";
					obj.put("stm", stm);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
				GlobalApplication.client.getSokect().sendTextMessage(obj.toString());
				imId += 1;
			}
		}, 1, 30000);
	}
	
	/**
	 * 获取平台基本信息（开盘时间、开盘价、收盘时间）
	 */
	private void getInfo(){
		InfoRequest request = new InfoRequest();
		C_Result result = request.info();
		String str = (String) result.mData;
		JSONObject jMsg = null;
		int message = 0;
		if(str!=null)
		try {
			jMsg = new JSONObject(str);
			if (jMsg != null) {
				trade = new Trade();
				if (!jMsg.isNull("trade_date")) {
					trade.setTrade_date( jMsg.getString("trade_date"));
				}
				if (!jMsg.isNull("open_time")) {
					trade.setOpen_time(jMsg.getString("open_time"));
				}
				if (!jMsg.isNull("close_time")) {
					trade.setClose_time(jMsg.getString("close_time"));
				}
				if (!jMsg.isNull("open_price")) {
					trade.setOpen_price( jMsg.getString("open_price"));
					mPrc.setOpenPrc(trade.getOpen_price());
					double open = Double.parseDouble(trade.getOpen_price());
					double up = open*0.1f+open;
					mPrc.setUpPrc(Util.dealStrs(up+"", 3));
					double down = open-open*0.1f;
					mPrc.setDownPrc(Util.dealStrs(down+"", 3));
				}
				if(!jMsg.isNull("decrease")){
					trade.setDecrease( jMsg.getString("decrease"));
				}
				if(!jMsg.isNull("increase")){
					trade.setIncrease( jMsg.getString("increase"));
				}
				message =8;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHandler.sendEmptyMessage(message);
	}
	/**
	 * 交易平台基本信息线程
	 * @author acer
	 *
	 */
	private class InfoTask extends AsyncTask<Void, Void, Void>{

		protected Void doInBackground(Void... arg0) {
			getInfo();
			return null;
		}		
	}
	
	/**
	 * 获取跑马灯
	 */
	private void getMarquee(){
		MarqueeRequest request = new MarqueeRequest();
		C_Result result = request.marquee();
		String str = (String) result.mData;
		JSONObject jMsg = null;
		int message = 11;
		if(str!=null)
		try {
			jMsg = new JSONObject(str);
			if (jMsg != null) {
				if(!jMsg.isNull("sm1")){
					marquees[0] = jMsg.getString("sm1");
				}
				if(!jMsg.isNull("sm2")){
					marquees[1] = jMsg.getString("sm2");
				}
				if(!jMsg.isNull("sm3")){
					marquees[2] = jMsg.getString("sm3");
				}
				message =14;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHandler.sendEmptyMessage(message);
	}
	
	private class MarqueeTask extends AsyncTask<Void, Void, Void>{

		protected Void doInBackground(Void... arg0) {
			getMarquee();
			return null;
		}		
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(fiveReceiver!=null){
			getActivity().unregisterReceiver(fiveReceiver);
			fiveReceiver = null;
		}
		if(pReceiver!=null){
			getActivity().unregisterReceiver(pReceiver);
			pReceiver = null;
		}
		if(imReceiver!=null){
			getActivity().unregisterReceiver(imReceiver);
			imReceiver = null;
		}
		if(moveReceiver!=null){
			getActivity().unregisterReceiver(moveReceiver);
			moveReceiver = null;
		}
		if(pTimer!=null){
			pTimer.cancel();
			pTimer = null;
		}
		if(fTimer!=null){
			fTimer.cancel();
			fTimer = null;
		}
		if(imTimer!=null){
			imTimer.cancel();
			imTimer = null;
		}
	}

}
